package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.Jwtproperties;
import com.sky.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.MonthTypeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
@Slf4j
public class JwtTokenAdminInteceptor implements HandlerInterceptor {

    @Autowired
    private Jwtproperties jwtproperties;
    /**
     * 拦截请求校验jwt
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到请求:{}", request.getRequestURI());
        if(!(handler instanceof HandlerMethod)){
            log.info("放行");
            return true;
        }
        String token = request.getHeader(jwtproperties.getAdminTokenName());
        //校验jwt
        try {
            Claims claims = JwtUtils.parseJwt(token, jwtproperties.getAdminSecretKey());
            //获取用户id
            Long empId = (Long)claims.get(JwtClaimsConstant.EMP_ID);
            log.info("当前用户id:{}", empId);
            BaseContext.setCurrentId(empId);
        } catch (Exception e) {
            // jwt校验失败,返回401
            response.setStatus(401);
            return false;
        }
        return true;
    }

}
